package com.echo.distributedlock.utils;

import com.alibaba.fastjson2.JSON;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @author lmy
 */
public class KeyUtil {

    public static String generateKey(String[] parameterNames, String name, String key, Object[] args) {
        StringBuilder stringBuffer = new StringBuilder(name);
        stringBuffer.append("::");
        String[] splits = key.split("#");
        for (String split : splits) {
            stringBuffer.append(generateKey(parameterNames, split, args));
        }
        return stringBuffer.toString();
    }

    private static String generateKey(String[] parameterNames, String key, Object[] args) {
        String[] keys = key.split("\\.");
        Object only = null;
        for (String item : keys) {
            if (Objects.isNull(only)) {
                only = getFirst(item, parameterNames, args);
                continue;
            }
            only = iteration(item, only);
        }
        return JSON.toJSONString(only);
    }

    private static Object getFirst(String key, String[] parameterNames, Object[] args) {
        int item = -1;
        if (key.contains("[") && key.contains("]")) {
            item = Integer.parseInt(key.substring(key.indexOf("[") + 1, key.indexOf("]")));
            key = key.substring(0, key.indexOf("["));
        }
        int flag = -1;
        for (String parameterName : parameterNames) {
            flag++;
            if (Objects.equals(parameterName, key)) {
                break;
            }
        }
        if (flag >= 0) {
            if (item >= 0) {
                return getKeyForArray(args[flag], item);
            }
            return args[flag];
        } else {
            throw new IllegalArgumentException("key值不存在");
        }
    }

    private static Object iteration(String key, Object object) {
        int item = -1;
        if (key.contains("[") && key.contains("]")) {
            item = Integer.parseInt(key.substring(key.indexOf("[") + 1, key.indexOf("]")));
            key = key.substring(0, key.indexOf("["));
            object = getKeyForObject(object, key);
        }
        if (item >= 0) {
            return getKeyForArray(object, item);
        } else {
            return getKeyForObject(object, key);
        }
    }

    private static Object getKeyForArray(Object object, int item) {
        if (!(object instanceof Collection)) {
            throw new IllegalArgumentException("key值不存在");
        }
        Collection<?> collection = (Collection<?>) object;
        Object[] objects = collection.toArray();
        return objects[item];
    }

    private static Object getKeyForObject(Object object, String keyName) {
        if (object instanceof Map) {
            return getKeyForMap(object, keyName);
        }
        return getKeyForEntity(object, keyName);
    }

    private static Object getKeyForMap(Object object, String keyName) {
        Map<String, Object> map = (Map<String, Object>) object;
        return map.get(keyName);
    }

    private static Object getKeyForEntity(Object object, String keyName) {
        try {
            Class<?> clazz = object.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (Objects.equals(field.getName(), keyName)) {
                    field.setAccessible(true);
                    return field.get(object);
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("key值不存在");
        }
        throw new IllegalArgumentException("key值不存在");
    }
}
